<?php

namespace app\controller;

use app\BaseController;
use app\model\Admin;
use app\logic\OauthLogic;
use app\service\PasswordService;
use think\Request;

class Oauth extends BaseController
{
    public function login(Request $request)
    {
        $Oauth = new OauthLogic();
        $token = $Oauth->login($request);
        if (!$token) {
            return JsonData(1001, "密码错误");
        }

        return JsonData(SUCCESS_CODE, "登录成功", ['token' => $token]);
    }

    public function installed()
    {
        $Oauth = new OauthLogic();
        if ($Oauth->getLock()) {
            return JsonData(SUCCESS_CODE, "已安装");
        }

        return JsonData(1001, "未安装");
    }

    public function register()
    {
        $Oauth = new OauthLogic();
        if ($Oauth->getLock()) {
            return JsonData(1002, "lock文件已存在,请先删除");
        }

        $password = $Oauth->register();
        if (!$password) {
            return JsonData(1001, "超级管理员初始化失败");
        }

        $Oauth->createLock();

        return JsonData(SUCCESS_CODE, "超级管理员初始化成功", ['username' => 'admin', 'password' => $password]);
    }

    public function changePassword(Request $request)
    {
        $Oauth = new OauthLogic();
        if ($Oauth->changePassword($request)) {
            return JsonData(SUCCESS_CODE, "管理员修改密码成功");
        }

        return JsonData(1001, "管理员修改密码失败");
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     */
    public function logout(Request $request)
    {
        $Oauth = new OauthLogic();
        $return = $Oauth->logout($request->header('token'));
        if (!$return) {
            return JsonData(1001, "失败");
        }
        return JsonData(SUCCESS_CODE, "成功");
    }
}
